﻿using System;
using System.Transactions;
using log4net;
using Xtensive.Storage;
using Transaction = Xtensive.Storage.Transaction;
using TransactionScope = Xtensive.Storage.TransactionScope;

namespace Sherwood.Content.DO
{
    public class SessionScope : IDataSessionScope
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(SessionScope));

        private readonly Session _session;
        private readonly TransactionScope _transactionScope;
        private readonly bool _sessionWasCreated;

        public SessionScope(SessionProvider sessionProvider, IsolationLevel isolationLevel)
            : this(Session.Open(sessionProvider.Domain), isolationLevel)
        {
            _sessionWasCreated = true;
        }

        public SessionScope(Session session, IsolationLevel isolationLevel)
        {
            if (session == null) throw new ArgumentNullException("session");

            _session = session;
            _transactionScope = Transaction.Open(isolationLevel);

            if (Log.IsDebugEnabled)
                Log.DebugFormat("Session scope created");
        }

        public void Dispose()
        {
            _transactionScope.Dispose();
            if (_sessionWasCreated)
                _session.Dispose();

            if (Log.IsDebugEnabled)
                Log.DebugFormat("Session scope closed");
        }

        public void Complete()
        {
            _transactionScope.Complete();

            if (Log.IsDebugEnabled)
                Log.DebugFormat("Transaction commited");
        }
    }
}